package com.hmdp.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@RequiredArgsConstructor
public class IdGenerator {
    // 用于同一毫秒内生成序列号
    private final StringRedisTemplate stringRedisTemplate;

    // 日期格式化器
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd");

    public Long generateOrderId(String prefixKey) {
        String date = LocalDateTime.now().format(formatter);
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + prefixKey + date, 1);

        String idStr = String.join("", date.split(":")) + count;
        return Long.parseLong(idStr);
    }
}
